<template>
  <div class="app-container">
    <div id="map"></div>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="附加商品名称" prop="productName">
        <el-input v-model="queryParams.productName" placeholder="请输入附加商品名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="适用门店" prop="storeName">
        <el-input v-model="queryParams.storeName" placeholder="请输入适用门店" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
          v-hasPermi="['business:addGood:query']">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['business:addGood:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['business:addGood:del']">批量删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="storeList" max-height="650px" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="适用区域" align="center" prop="regionName" :show-overflow-tooltip="true" width="120" />
      <el-table-column label="适用门店" align="center" prop="storeName" :show-overflow-tooltip="true" />
      <el-table-column label="商品名称" align="center" prop="productName" :show-overflow-tooltip="true" />
      <el-table-column label="售卖价" align="center" prop="originalPrice" />
      <el-table-column label="成本价" align="center" prop="costPrice" />

      <el-table-column label="提成金额" align="center" prop="royalty" />
      <el-table-column label="排序" align="center" prop="orderNum" />
      <el-table-column label="上架" align="center" prop="status">
        <template slot-scope="scope">
          <span>{{ scope.row.status == "1" ? "上架" : "下架" }}</span>
        </template>
      </el-table-column>

      <el-table-column label="小程序是否显示" align="center" prop="status">
        <template slot-scope="scope">
          <span>{{ scope.row.minproIsshow == 1 ? "显示" : "不显示" }}</span>
        </template>
      </el-table-column>


      <el-table-column label="创建人" align="center" prop="createBy" />

      <el-table-column label="创建时间" align="center" prop="createTime" />

      <el-table-column label="修改人" align="center" prop="updateBy" />

      <el-table-column label="修改时间" align="center" prop="updateTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="250">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['business:addGood:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-upload2" @click="handleGround(scope.row, (status = 1))"
            v-hasPermi="['business:addGood:Listing']" :disabled="scope.row.status === 1">上架</el-button>
          <el-button size="mini" type="text" icon="el-icon-download" @click="handleGround(scope.row, (status = 2))"
            v-hasPermi="['business:addGood:offShelf']" :disabled="scope.row.status === 2">下架</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" :disabled="scope.row.status === 1"
            @click="handleDelete(scope.row)" v-hasPermi="['business:addGood:del']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <!-- 添加或修改门店对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="附加商品名称" prop="productName">
              <el-input v-model="form.productName" placeholder="请输入附加商品名称" style="width: 222px" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="区域" prop="regionId">
              <el-select clearable v-model="form.regionIds" @change="changeRegion" multiple>
                <el-option v-for="(item, index) of region" :key="index" :label="item.value" :value="item.key">{{
                  item.value
                }}</el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="适用门店" prop="storeId">
              <el-select clearable v-model="form.storeIds" @change="changeStore" multiple>
                <el-option v-for="(item, index) of store" :key="index" :label="item.value" :value="item.key">{{
                  item.value
                }}</el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="正常价" prop="originalPrice">
              <!-- @input="handleInput" -->
              <el-input @input="
                (value) =>
                  (this.form.originalPrice = value.replace(/[^\d]/g, ''))
              " v-model="form.originalPrice" placeholder="请输入正常价" style="width: 222px" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="成本价" prop="costPrice">
              <el-input @input="
                (value) => (this.form.costPrice = value.replace(/[^\d]/g, ''))
              " v-model="form.costPrice" placeholder="请输入成本价" style="width: 222px" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="提成金额" prop="royalty">
              <el-input @input="
                (value) => (this.form.royalty = value.replace(/[^\d]/g, ''))
              " v-model="form.royalty" placeholder="请输入提成金额" style="width: 222px" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="小程序端是否显示" prop="minproIsshow">
              <el-select clearable v-model="form.minproIsshow">
                <el-option v-for="(item, index) of isShowList" :key="index" :label="item.value" :value="item.key">{{
                  item.value }}</el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上架状态" prop="status">
              <el-select clearable v-model="form.status">
                <el-option v-for="(item, index) of List" :key="index" :label="item.value" :value="item.key">{{
                  item.value
                }}</el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="顺序" prop="orderNum">
              <el-input v-model="form.orderNum" placeholder="顺序" style="width: 222px" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- <el-form-item label="项目图片" prop="img">
          <image-upload v-model="form.img" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listitemList,
  getItemProduct,
  delitemProduct,
  addItemProduct,
  updateitemProduct,
  listMemberRegion,
  listMemberStore,
} from "@/api/system/projectList/addGood";

export default {
  name: "Store",
  data() {
    return {
      map: null,
      local: null,
      mk: null,
      latitude: "",
      longitude: "",
      keyWords: "",
      result: "",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 门店表格数据
      storeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      /////////
      isShowList: [
        {
          key: 1,
          value: "是",
        },
        {
          key: 2,
          value: "否",
        },
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: null,
        storeName: null,
        storeName: null,
        phoneNumber: null,
        province: null,
        provinceString: null,
        city: null,
        cityString: null,
        county: null,
        countyString: null,
        detail: null,
        longitude: null,
        latitude: null,
        intro: null,
        images: null,
        status: null,
        isInitiate: null,
        openingTime: null,
        closingTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        minproIsshow: [
          {
            required: true,
            message: "请选择是否展示小程序端",
            trigger: "blur",
          },
        ],
        productName: [
          { required: true, message: "请输入附加商品名称", trigger: "blur" },
        ],
        // img: [{ required: true, message: "请选择", trigger: "blur" }],
        regionId: [{ required: true, message: "请选择", trigger: "blur" }],
        storeId: [{ required: true, message: "请选择", trigger: "blur" }],
        originalPrice: [
          { required: true, message: "请输入正常价", trigger: "blur" },
          {
            pattern: /^(0|[1-9]\d{0,2})(\.\d+)?$/,
            message: "请输入正确正常价，价格不得大于一千",
            trigger: "blur"
          },
        ],
        royalty: [
          { required: true, message: "请输入提成金额", trigger: "blur" },
          {
            pattern: /^-?\d+(\.\d+)?$/,
            message: "请输入正确提成金额",
            trigger: "blur",
          },
        ],
        status: [
          { required: true, message: "请选择", trigger: "blur" },
          { pattern: /^-?\d+(\.\d+)?$/, message: "请选择", trigger: "blur" },
        ],
      },
      options: [],
      List: [
        {
          key: 1,
          value: "上架",
        },
        {
          key: 2,
          value: "下架",
        },
      ],
      region: [],
      store: [],
      productName: [],
    };
  },
  created() {
    this.getList();
    this.listregion();
  },
  methods: {
    listregion() {
      listMemberRegion().then((res) => {
        this.region = res.data.map((rItem) => {
          return {
            key: rItem.id,
            value: rItem.regionName,
          };
        });
      });
    },
    changeRegion(value) {
      // const selectedOption = this.region.find((item) => item.key === value);
      // const selectedKey = selectedOption.key;
      // const selectedValue = selectedOption.value;
      // console.log(`Selected Key: ${selectedKey}`);
      // console.log(`Selected Value: ${selectedValue}`);
      // this.form.regionName = selectedValue;
      console.log(value);
      let arr = [];
      arr = value.map((val) => {
        let obj = this.region.find((item) => item.key == val);
        console.log(obj);
        return (obj && obj.value) || val;
      });
      console.log(arr);
      const regionStr = value.length > 1 ? value.join(",") : value[0];
      this.form.regionId = value[0];
      this.form.regionName = arr.join(",");
      // listMemberStore({ regionIds: regionStr }).then((res) => {
      //   console.log(res, 333);
      //   this.store = res.data.map((rItem) => {
      //     return {
      //       key: rItem.id,
      //       value: rItem.storeName,
      //     };
      //   });
      // });
      this.getStoreList();
    },
    changeStore(value) {
      // const selectedOption = this.store.find((item) => item.key === value);
      // const selectedKey = selectedOption.key;
      // const selectedValue = selectedOption.value;
      // console.log(`Selected Key: ${selectedKey}`);
      // console.log(`Selected Value: ${selectedValue}`);
      // this.form.storeName = selectedValue;
      let arr = [];
      value.map((val) => {
        console.log(this.store.find((item) => item.key === val));
        arr.push(this.store.find((item) => item.key === val).value);
        return val;
      });
      this.form.storeId = value[0];
      this.form.storeName = arr.join(",");
    },
    /** 查询门店列表 */
    getList() {
      this.loading = true;
      listitemList(this.queryParams).then((response) => {
        this.storeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.resetForm("form");

      this.form = {
        id: null,
        storeName: null,
        phoneNumber: null,
        province: null,
        provinceString: null,
        city: null,
        cityString: null,
        county: null,
        countyString: null,
        detail: null,
        longitude: null,
        latitude: null,
        intro: null,
        minproIsshow: null,
        status: null,
        images: null,
        isInitiate: null,
        openingTime: null,
        closingTime: null,
        createTime: null,
        updateTime: null,
      };
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.productName = selection.map((item) => item.productName);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加门店附加商品";
    },
    // 上下架
    handleGround(row, status) {
      const params = {
        id: row.id,
        status: status,
      };
      this.$confirm(
        `此操作将${status === 1 ? "上架" : "下架"}该数据, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          updateitemProduct(params).then((res) => {
            this.$message({
              type: "success",
              message: `${status === 1 ? "上架" : "下架"}成功!`,
            });
            this.getList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消上下架",
          });
        });
    },
    getStoreList() {
      let value = this.form.regionIds;
      console.log(value);
      const regionStr = value && value.length > 0 ? value.join(",") : "";
      listMemberStore({ regionIds: regionStr }).then((res) => {
        this.store = res.data.map((rItem) => {
          return {
            key: rItem.id,
            value: rItem.storeName,
          };
        });
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      // this.reset();
      const id = row.id || this.ids;
      getItemProduct(id).then((response) => {
        this.form = response.data;

        let regionIds = this.form.regionIds && this.form.regionIds.split(",");
        this.form.regionIds = regionIds.map((ele) => ele - 0);

        this.getStoreList();
        let storeIds = this.form.storeIds && this.form.storeIds.split(",");
        this.form.storeIds = storeIds.map((ele) => ele - 0);

        this.open = true;
        this.title = "修改门店附加商品";
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (Array.isArray(this.form.regionIds)) {
          this.form.regionIds = this.form.regionIds.join(",");
        } else {
          this.form.regionIds = this.form.regionIds[0];
        }

        if (Array.isArray(this.form.storeIds)) {
          this.form.storeIds = this.form.storeIds.join(",");
        } else {
          this.form.storeIds = this.form.storeIds[0];
        }

        // this.form.regionIds =
        //   this.form.regionIds.length > 1
        //     ? this.form.regionIds.join(",")
        //     : this.form.regionIds[0];
        // this.form.storeIds =
        //   this.form.storeIds.length > 1
        //     ? this.form.storeIds.join(",")
        //     : this.form.storeIds[0];

        console.log(this.form, "form");

        if (valid) {
          if (this.form.id != null) {
            updateitemProduct(this.form).then((response) => {
              if (response.code == 200) {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addItemProduct(this.form).then((response) => {
              if (response.code == 200) {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    handReset(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认重置编号为"' + ids + '"的数据项？')
        .then(function () {
          return listResetPwd({ userId: ids });
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("重置成功");
        })
        .catch(() => { });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除编号为"' + ids + '"的数据项？')
        .then(function () {
          return delitemProduct(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/store/export",
        {
          ...this.queryParams,
        },
        `store_${new Date().getTime()}.xlsx`
      );
    },
    handleInput(value) {
      // 过滤掉非数字和非小数点的字符
      let newVal = value.replace(/[^\d.]/g, '');
      // 处理多个小数点的情况
      const dotCount = (newVal.match(/\./g) || []).length;
      if (dotCount > 1) {
        newVal = newVal.slice(0, newVal.lastIndexOf('.'));
      }
      // 保留小数点后最多两位
      const dotIndex = newVal.indexOf('.');
      if (dotIndex !== -1) {
        newVal = newVal.slice(0, dotIndex + 3);
      }
      this.form.originalPrice = newVal;
    }
  },
};
</script>
<style>
.dialog-footer {
  text-align: center;
}
</style>
